/*
    This file is part of Posixcpp library.

    Posixcpp library is free software: you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public License
    as published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Posixcpp library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU LesserGeneral Public
    License along with Posixcpp library. If not, see
    <http://www.gnu.org/licenses/>.
*/

#include "posix_io_file.hpp"

using posix::io::IFile;
using posix::io::File;

File::File( ) :
m_accessMode(AccessMode_t::READ_ONLY),
m_customFlags(0) {

}

File::File( const std::string& fileName ) :
m_fileName(fileName),
m_accessMode(AccessMode_t::READ_ONLY),
m_customFlags(0) {

}


void File::create( ) {
    
    PRECONDITION_ASSERT( m_descriptor == -1, "file already opened" );
	PRECONDITION_ASSERT( !m_fileName.empty(), "empty file name" );
	PRECONDITION_ASSERT( m_fileName != "", "empty file name" );
    
    POSIX_CALL_ASSERT( (m_descriptor = ::creat(m_fileName.c_str(),
            m_mode.data() )) != -1 );
}

void File::create( const std::string& fileName, Mode mode ) {
    
    this->setFileName( fileName );
    this->setMode( mode );
    this->create();
}

void File::open() {
    
	PRECONDITION_ASSERT( m_descriptor == -1, "file already opened" );
	PRECONDITION_ASSERT( !m_fileName.empty(), "empty file name" );
	PRECONDITION_ASSERT( m_fileName != "", "empty file name" );
	
	std::string message("Unable to open file (");
	message.append(m_fileName).append(")");
	
	POSIX_CALL_ASSERT_X( (m_descriptor =
						::open(m_fileName.c_str(),
							int(m_accessMode) | int(m_blockingMode) | m_customFlags )) != -1,
						message.c_str() );
}

void File::open(
  const std::string& fileName,
  Mode mode ) {
    
    this->setFileName(fileName);
    this->setMode( mode );
    this->open();
}
